package org.sky.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

public class XmlAnalyzeUtil {
	public static String getXml(HttpServletRequest request){
		// 从request中取得输入流  
        InputStream inputStream = null;
        Document document = null;
        // 读取输入流  
        SAXReader reader = new SAXReader(); 
		try {
			inputStream = request.getInputStream();
			try {
				document = reader.read(inputStream);
				inputStream.close();
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		} 
    	return document.asXML();
	}
	
	public static String toXml(Object object){
			//String head="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
			xstream.alias("xml", object.getClass());
			return xstream.toXML(object);
	}
	 /** 
     * 扩展xstream，使其支持CDATA块 
     *  
     * @date 2013-05-19 
     */  
    private static XStream xstream = new XStream(new XppDriver() {  
        public HierarchicalStreamWriter createWriter(Writer out) {  
            return new PrettyPrintWriter(out) {  
                // 对所有xml节点的转换都增加CDATA标记  
                boolean cdata = true;  
  
                public void startNode(String name, Class clazz) {  
                    super.startNode(name, clazz);  
                }  
  
                protected void writeText(QuickWriter writer, String text) {  
                    if (cdata) {  
                        writer.write("<![CDATA[");  
                        writer.write(text);  
                        writer.write("]]>");  
                    } else {  
                        writer.write(text);  
                    }  
                }  
            };  
        }  
    });  
}	
